package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeeResetPasswordDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 前端传来的明文密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);
        //设置账号的状态，默认正常状态 1表示正常 0表示锁定
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码，默认密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

//        //设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //设置当前记录创建人id和修改人id
//        employee.setCreateUser(BaseContext.getCurrentId());//每次请求，创建一个threadLocal，里面保存了当前登录用户的id
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);//后续步骤定义
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        return new PageResult(total,page.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
//        Employee employee = new Employee();
//        employee.setStatus(status);
//        employee.setId(id);
        Employee employee = Employee.builder().status(status).id(id).build();
        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    // EmployeeServiceImpl.java
    @Override
    public void register(EmployeeDTO employeeDTO) {
        log.info("员工注册：{}", employeeDTO);

        String username = employeeDTO.getUsername();
        String password = employeeDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee existingEmployee = employeeMapper.getByUsername(username);

        //2、处理异常情况（用户名已存在）
        if (existingEmployee != null) {
            //用户名已存在
            throw new UsernameExistsException(MessageConstant.USERNAME_EXISTS);
        }

        //3、创建新员工并设置属性
        Employee employee = new Employee();

        // 使用BeanUtils拷贝属性（除了密码）
        BeanUtils.copyProperties(employeeDTO, employee, "password");

        // 对前端传来的密码进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        // 设置状态
        employee.setStatus(StatusConstant.ENABLE);

        // 设置时间信息
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 设置操作用户
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);

        //4、插入数据库
        employeeMapper.insert(employee);

        log.info("员工注册成功，用户名：{}", username);
    }
    @Override
    public String sendResetCode(String phone) {
        log.info("发送密码重置验证码：{}", phone);

        // 1. 验证手机号是否存在
        Employee employee = employeeMapper.getByPhone(phone);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 2. 生成6位随机验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));

        // 3. 将验证码存入Redis，设置5分钟过期
        String redisKey = "reset_code:" + phone;
        redisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);

        // 4. 记录日志并返回验证码（前端会以弹窗形式显示）
        log.info("手机号 {} 的密码重置验证码：{}", phone, code);

        return code; // 返回验证码给前端显示
    }

// resetPassword 方法保持不变...

    @Override
    public void resetPassword(EmployeeResetPasswordDTO resetPasswordDTO) {
        log.info("重置密码：{}", resetPasswordDTO);

        String phone = resetPasswordDTO.getPhone();
        String newPassword = resetPasswordDTO.getNewPassword();
        String code = resetPasswordDTO.getCode();

        // 1. 验证验证码
        String redisKey = "reset_code:" + phone;
        String storedCode = (String) redisTemplate.opsForValue().get(redisKey);

        if (storedCode == null) {
            throw new CodeExpiredException(MessageConstant.CODE_EXPIRED);
        }

        if (!storedCode.equals(code)) {
            throw new CodeErrorException(MessageConstant.CODE_ERROR);
        }

        // 2. 根据手机号查询员工
        Employee employee = employeeMapper.getByPhone(phone);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 3. 更新密码
        Employee updateEmployee = new Employee();
        updateEmployee.setId(employee.getId());
        updateEmployee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        updateEmployee.setUpdateTime(LocalDateTime.now());
        updateEmployee.setUpdateUser(employee.getId()); // 使用员工自己的ID

        employeeMapper.update(updateEmployee);

        // 4. 删除已使用的验证码
        redisTemplate.delete(redisKey);

        log.info("密码重置成功，手机号：{}", phone);
    }

    @Override
    public String getUsernameByPhone(String phone) {
        log.info("根据手机号查询用户名：{}", phone);

        // 1. 根据手机号查询员工信息
        Employee employee = employeeMapper.getByPhone(phone);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 2. 返回用户名
        return employee.getUsername();
    }
}
